<?php

namespace app\api\server\user;

use app\api\model\coupon\CouponApiModel;
use app\api\model\user\UserCouponApiModel;
use app\api\ServerBase;
use think\facade\Db;
use think\Request;

class UserCouponServer extends ServerBase
{


    /**
     * @var array|mixed
     */
    private $param;

    function __construct(Request $request)
    {
        $this->request=$request;
        $this->param=$request->param();
        $this->model = new UserCouponApiModel();
        $this->couponModel = new CouponApiModel();
    }

    function getList(){
        [$page,$limit] = $this->getPage($this->param);
        $this->param['status'] = $this->param['status']??1;
        $this->param['user_id'] = $this->request->user_id;
        [$list,$count] = $this->model->getApiList($this->param,'id,coupon_id,status,create_time,expire_time',$page,$limit);
        $result['data']=$list;
        $result['count']=$count;
        $this->getMessageCode('adminMessage.success.select',2);
        return $result;
    }

    function receive(){
        $id = $this->param['id']??0;
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        $coupon = $this->couponModel->getFindById($id);
        if(empty($coupon)){
            $this->ERROR='优惠券不存在';
            return false;
        }
        if($coupon['num'] == 0 || ($coupon['num'] != -1 && $coupon['num']-1 <=0) ){
            $this->ERROR='优惠券已领完';
            return false;
        }
        $has = $this->model::isHaveByCouponId($id,$this->request->user_id);
        if($has){
            $this->ERROR='已领取过优惠券';
            return false;
        }
        Db::startTrans();
        try {
            $this->model->save([
                'user_id'=>$this->request->user_id,
                'coupon_id'=>$id,
                'expire_time'=>$coupon['expire_days'] == -1 ?
                    '2099-12-31 23:59:59':
                    date('Y-m-d 23:59:59',time()+$coupon['expire_days']*86400),
            ]);
            $coupon->save(['num'=>$coupon['num']-1]);
            Db::commit();
            return true;
        }catch (\Exception $exception){
            Db::rollback();
            $this->ERROR=$exception->getMessage();
            return false;
        }
    }
}